<template>
  <a-modal
    :title='model ? "编辑曲线": "添加曲线"'
    :width='1040'
    :visible='visible'
    :confirmLoading='loading'
    @ok='handleSubmit'
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning='loading'>
      <a-form :form='form' v-bind='formLayout'>
        <a-form-item label='主键' v-show='false'>
          <a-input v-decorator="['id']" />
        </a-form-item>

        <a-form-item label='曲线名称'>
          <a-input v-decorator="[
              'reportName',
              { rules: [{ required: true, message: '请输入曲线名称!' },
             { pattern: namePattern,  message: '请输入合法内容(可输入0到50位（中文、字母，数字，下划线，减号)'}
              ] },
            ]" />
        </a-form-item>

        <a-form-item>
          <span slot='label'>
            曲线类型
          </span>
          <a-select v-decorator="[
            'reportTypeDicId',
            { rules: [{ required: true, message: '请选择曲线类型!' }] },
          ]" :options='reportTypeList' />
        </a-form-item>

        <a-form-item v-bind='index === 0 ? formItemLayout : formItemLayoutWithOutLabel'
                     v-for="(k, index) in form.getFieldValue('options')" :key='k.id'>
          <span slot='label' v-if='index === 0'>
            {{ index === 0 ? '监控项' : '' }}
             <a-tooltip>
              <template slot='title'>
                饼图暂不支持设置监控项颜色
              </template>
              <a-icon style='cursor: pointer' type='exclamation-circle' />
            </a-tooltip>
          </span>
          <a-row>
            <a-col :span='4'>
              <a-select
                allowClear
                style='width:100%'
                :options='systemList'
                placeholder='请选择系统'
                @change='val=>handleChangeSystem(val, index)'
                v-decorator="[`systemIdList[${k.id}]`,{ rules: [{ required: true, message: '请选择系统' }], initialValue: formModel && formModel.systemIdList && formModel.systemIdList[k.id]} ]">
              </a-select>
            </a-col>

            <a-col :span='4' :offset='1'>
              <a-select
                style='width:100%'
                allowClear
                :options='deviceList[index]'
                placeholder='请选择设备'
                @change='val=>handleChangeDevice(val, index)'
                v-decorator="[`deviceIdList[${k.id}]`,{ rules: [{ required: true, message: '请选择设备' }], initialValue: formModel && formModel.deviceIdList && formModel.deviceIdList[k.id] }]">
              </a-select>
            </a-col>

            <a-col :span='4' :offset='1'>
              <a-select
                style='width:100%'
                allowClear
                :options='pointList[index]'
                placeholder='请选择点位'
                @change='val=>handleChangePoint(val, index)'
                v-decorator="[`pointIdList[${k.id}]`,{ rules: [{ required: true, message: '请选择点位' }],  initialValue: formModel && formModel.pointIdList && formModel.pointIdList[k.id] }]">
              </a-select>
            </a-col>

            <a-col :span='5' :offset='1'>
              <a-input placeholder='请输入显示名称'
                       v-decorator='[`displayNameList[${k.id}]`,{ initialValue: formModel && formModel.displayNameList && formModel.displayNameList[k.id]  }]' />
            </a-col>
            <a-col :span='3' :offset='1'>
              <a-row>
                <a-col :span='12'>
                  <color-picker
                    :disabled='+form.getFieldValue("reportTypeDicId") === 49'
                    v-decorator='[`colorList[${k.id}]`, {  initialValue: formModel && formModel.colorList && formModel.colorList[k.id]}] || "#4470d8"' />
                </a-col>
                <a-col :span='12'>
                  <a-icon
                    v-if="form.getFieldValue('options').length > 1"
                    class='dynamic-delete-button'
                    type='minus-circle-o'
                    style='color: red'
                    :disabled="form.getFieldValue('options').length === 1"
                    @click='() => remove(k)'
                  />
                </a-col>
              </a-row>
            </a-col>
          </a-row>
        </a-form-item>
        <a-row>
          <a-button type='dashed' style='width: 100%' @click='add'>
            <a-icon type='plus' />
            增加监控项
          </a-button>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import ColorPicker from '@/components/ColorPicker/index.vue'
import pick from 'lodash.pick'
import { findAllDeviceBySystemId, findAllPointByDeviceId, findAllSystemByModuleId } from '@/api/historyTime'
import { findDataDicInfoByType } from '@/api/dataDicInfo'
import { namePattern } from '@/reges/index'
// 表单字段
const fields = ['id', 'reportName', 'reportTypeDicId', 'systemIdList', 'deviceIdList', 'pointIdList', 'displayNameList', 'colorList', 'systemNameList', 'deviceNameList', 'pointNameList']

let id = 0
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    moduleId: {
      type: String,
      default: ''
    }
  },
  components: {
    ColorPicker
  },
  data() {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 }
      }
    }
    return {
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 3 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 21 }
        }
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 21, offset: 3 }
        }
      },
      namePattern,
      formModel: {},
      systemList: [],
      systemId: '',
      deviceId: '',
      deviceList: [],
      pointList: [],
      reportTypeList: []
    }
  },
  created() {
    // 防止表单未注册
    this.getReportTypeList()
    this.findAllSystemByModuleId()
    // 当 model 发生改变时，为表单设置值
    this.form.getFieldDecorator('options', { initialValue: [{ id }], preserve: true })
    this.form.getFieldDecorator('systemNameList', { initialValue: [], preserve: true })
    this.form.getFieldDecorator('deviceNameList', { initialValue: [], preserve: true })
    this.form.getFieldDecorator('pointNameList', { initialValue: [], preserve: true })
    this.$watch('model', async () => {
      this.formModel = this.model
      fields.forEach(v => this.form.getFieldDecorator(v))
      this.model && this.form.setFieldsValue(pick(this.model, fields))
      await this.initSelectList()
    })
  },
  methods: {
    handleSubmit() {
      let {
        systemIdList,
        deviceIdList,
        pointIdList
      } = this.form.getFieldsValue(['systemIdList', 'deviceIdList', 'pointIdList'])
      if (!systemIdList.length || !deviceIdList.length || !pointIdList.length) {
        this.$message.error('监控项中的系统,设备,点位存在必填内容未填写!')
        return
      }
      systemIdList = systemIdList.filter(item => !item)
      deviceIdList = deviceIdList.filter(item => !item)
      pointIdList = pointIdList.filter(item => !item)
      if (systemIdList.length || deviceIdList.length || pointIdList.length) {
        this.$message.error('监控项中的系统,设备,点位存在必填内容未填写!')
        return
      }
      this.$emit('ok')
    },
    validatorPhone(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入设备名称'))
      } else {
        if (!/^\S*$/.test(value)) {
          callback(new Error('请勿输入空格等特殊字符!'))
        } else {
          callback()
        }
      }
    },
    async initSelectList() {
      if (!this.formModel) {
        return
      }
      const systemIdList = this.formModel.systemIdList
      const deviceIdList = this.formModel.deviceIdList
      const that = this
      let optionsList = []
      for (let i = 0; i < systemIdList.length; i++) {
        optionsList.push({ id: i })
        await that.findAllDeviceBySystemId(systemIdList[i], i)
        await that.findAllPointByDeviceId(deviceIdList[i], i)
      }
      if(systemIdList.length){
        id = systemIdList.length - 1
        this.form.setFieldsValue({
          options: optionsList
        })
      }
    },
    handleChangeSystem(val, index) {
      const deviceIdList = this.form.getFieldValue('deviceIdList')
      const pointIdList = this.form.getFieldValue('pointIdList')
      const systemNameList = this.form.getFieldValue('systemNameList')
      deviceIdList[index] = ''
      pointIdList[index] = ''
      systemNameList[index] = this.systemList.find(item => item.key === val)['label']
      this.form.setFieldsValue({
        deviceIdList,
        pointIdList,
        systemNameList
      })
      if (!val) {
        return
      }
      this.findAllDeviceBySystemId(val, index)
    },
    handleChangeDevice(val, index) {
      const pointIdList = this.form.getFieldValue('pointIdList')
      const deviceNameList = this.form.getFieldValue('deviceNameList')
      pointIdList[index] = ''
      deviceNameList[index] = this.deviceList[index].find(item => item.key === val)['label']
      this.form.setFieldsValue({
        pointIdList,
        deviceNameList
      })
      if (!val) {
        return
      }
      this.findAllPointByDeviceId(val, index)
    },
    handleChangePoint(val, index) {
      const pointNameList = this.form.getFieldValue('pointNameList')
      pointNameList[index] = this.pointList[index].find(item => item.key === val)['label']
      this.form.setFieldsValue({
        pointNameList
      })
    },
    async getReportTypeList() {
      const result = await findDataDicInfoByType(11)
      this.reportTypeList = result.map(item => {
        return {
          ...item,
          key: Number(item.id),
          label: item.name
        }
      })
    },
    // 查询点位
    async findAllPointByDeviceId(val, index) {
      this.$emit('up-loading', true)
      try {
        const result = await findAllPointByDeviceId({
          deviceId: val,
          moduleId: this.moduleId
        })
        this.pointList[index] = result.map(item => {
          return {
            ...item,
            key: item.positionId,
            label: item.positionName
          }
        })
        this.$forceUpdate()
      } finally {
        this.$emit('up-loading', false)
      }
    },
    // 查询设备
    async findAllDeviceBySystemId(val, index) {
      this.$emit('up-loading', true)
      try {
        const result = await findAllDeviceBySystemId({
          systemId: val,
          moduleId: this.moduleId
        })
        this.deviceList[index] = result.map(item => {
          return {
            ...item,
            key: item.deviceId,
            label: item.deviceName
          }
        })
        this.$forceUpdate()
      } finally {
        this.$emit('up-loading', false)
      }
    },
    remove(value) {
      const { form } = this
      const { id: currentId } = value
      // can use data-binding to get
      const options = form.getFieldValue('options')
      // We need at least one passenger
      if (options.length === 1) {
        return
      }

      // can use data-binding to set
      form.setFieldsValue({
        options: options.filter(item => item.id !== currentId)
      })
    },

    add() {
      const { form } = this
      const options = form.getFieldValue('options')
      id++
      form.setFieldsValue({
        options: [...options, { id }]
      })
    },
    async findAllSystemByModuleId() {
      this.$emit('up-loading', true)
      try {
        const result = await findAllSystemByModuleId({ moduleId: this.moduleId })
        this.systemList = result.map(item => {
          return {
            ...item,
            key: item.systemId,
            label: item.systemName
          }
        })
      } finally {
        this.$emit('up-loading', false)
      }
    }
  }
}
</script>
